#include "../corelib/mysql/mysql.hh"
#include "unittest/unittest.hh"
#include <cstring>
#include <cstdlib>
#include <chrono>

//
// NOTICE open testcases of MySQL, please startup a mysqld server
//

#define MYSQL_HOST "192.168.2.28"
#define MYSQL_PORT 3306
#define MYSQL_USER "root"
#define MYSQL_PASS "test"
#define MYSQL_DB ""

using namespace kratos::mysql;

FIXTURE_BEGIN(MySQL)

CASE(TestAddHost) {
    ASSERT_TRUE(MySQLRef.addHost("test", MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PASS, MYSQL_DB, 2));
    ASSERT_FALSE(MySQLRef.addHost("test", "1.2.3.4", MYSQL_PORT, MYSQL_USER, MYSQL_PASS, MYSQL_DB, 2));
    MySQLRef.stop();
}

CASE(TestFindConn) {
    ASSERT_TRUE(MySQLRef.addHost("test", MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PASS, MYSQL_DB, 2));
    ASSERT_TRUE(MySQLRef.findConn("test"));
    ASSERT_FALSE(MySQLRef.findConn("123"));
    MySQLRef.stop();
}

CASE(TestStart) {
    MySQLConn conn(MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PASS, MYSQL_DB);
    ASSERT_TRUE(conn.start());
    ASSERT_FALSE(MySQLConn("").start());
    ASSERT_FALSE(MySQLConn("1.1.1.1").start());
}

CASE(TestStop) {
    MySQLConn conn(MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PASS, MYSQL_DB);
    ASSERT_TRUE(conn.start());
    conn.stop();
    conn.stop();
}

CASE(TestDoCommand1) {
    MySQLConn conn(MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PASS, MYSQL_DB);
    ASSERT_TRUE(conn.start());
    bool ok = false;
    conn.doCommand("select unix_timestamp();", 1, 1,
        [&](MySQLResult& result) {
            ok = !result.getErrorID() && (1 == result.getUserData()) && (1 == result.getTaskID());
        }
    );
    std::this_thread::sleep_for(std::chrono::seconds(1));
    conn.update(0);
    ASSERT_TRUE(ok);
}

CASE(TestDoCommand2) {
    MySQLConn conn(MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PASS, MYSQL_DB);
    ASSERT_TRUE(conn.start());
    bool ok = false;
    conn.doCommand("sdfdsfsdfdfdf", 1, 1,
        [&](MySQLResult& result) {
            ok = !result.getErrorID();
        }
    );
    std::this_thread::sleep_for(std::chrono::seconds(1));
    conn.update(0);
    ASSERT_FALSE(ok);
}

CASE(TestDoCommand3) {
    MySQLConn conn(MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PASS, MYSQL_DB);
    ASSERT_TRUE(conn.start());
    ASSERT_FALSE(conn.doCommand(""));
}

CASE(TestDoCommand4) {
    MySQLConn conn(MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PASS, MYSQL_DB);
    ASSERT_TRUE(conn.start());
    conn.stop();
    ASSERT_FALSE(conn.doCommand("select unix_timestamp();"));
}

FIXTURE_END(MySQL)
